package com.tbgov.service;

import com.alibaba.fastjson2.JSONObject;
import com.tbgov.constant.RedisKeyConst;
import com.tbgov.entity.pojo.Token;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.concurrent.TimeUnit;

/**
 * @author 1st
 */
@Service
@RequiredArgsConstructor
public class RedisTokenService {

    final StringRedisTemplate redisTemplate;

    public void storeToken(Token token) {
        redisTemplate.opsForValue().set(token.getToken(), JSONObject.toJSONString(token), RedisKeyConst.TOKEN_EXPIRATION_TIME, TimeUnit.MILLISECONDS);
    }

    public String getLoginUser(String tk) {
        // 如果过期会自动返回 null
        return redisTemplate.opsForValue().get(tk);
    }

    public void deleteToken(String tk) {
        redisTemplate.delete(tk);
    }



    public void verifyCode(String phoneNumber, String code) {
        String redisCode = redisTemplate.opsForValue().get(getRedisKey(phoneNumber));
        Assert.isTrue(redisCode != null, "验证码已过期或不存在！");
        if (redisCode.equals(code)) {
            // 验证成功后删除缓存
            redisTemplate.delete(getRedisKey(phoneNumber));
        } else {
            throw new IllegalArgumentException("验证码错误！");
        }
    }

    public String getRedisKey(String phoneNumber) {
        return "sms:verification:" + phoneNumber;
    }
}
